/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ejb;

import entities.Category;
import entities.Item;
import entities.User;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.NoResultException;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.validation.ConstraintViolationException;

/**
 *
 * @author Alejandro
 */
@Stateless
public class ItemBean implements ItemBeanLocal {

    @PersistenceContext(unitName = "Retailshop-ejbPU")
    // @PersistenceUnit
    EntityManager manager;

    @Override
    public void addItem(Item item) {
        // manager.getTransaction().begin();
        try {
            if (item.getRegistrationDate() == null) {
                item.setRegistrationDate(new Date());
            }

            manager.merge(item);
        } catch (ConstraintViolationException e) {
            e.printStackTrace();
        }
        // manager.getTransaction().commit();
    }

    @Override
    public List<Item> findByIdCategory(Category category) {
        Query query = manager.createNamedQuery("Item.findByIdCategory");

        query.setParameter("idCategory", category);

        return (List<Item>) query.getResultList();
    }

    @Override
    public List<Item> findAll() {
        List<Item> res = null;
        Query query = manager.createNamedQuery("Item.findAll");

        try {
            res = (List<Item>) query.getResultList();
        } catch (NoResultException e) {
            return null;
        }
        return res;
    }
    
    @Override
    public List<Item> findAllActives() {
        List<Item> res = null;
        Query query = manager.createNamedQuery("Item.findAllActives");

        try {
            res = (List<Item>) query.getResultList();
        } catch (NoResultException e) {
            return null;
        }
        return res;
    }
}
